package models;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import play.db.jpa.Model;
 
public class TweetGrabber 
{
	static TweetGrabber tg;
	static XMLoutput xmlo;
	static NoiseFilter nf;
	static SentFilter sf;
	static SQLwork sqlw;
	
	private File file = new File("Tweetalyze/app/temp.xml");
	
	private static ArrayList <Tweet> tweets;
	private Tweet tempTweet;
	
	public static ArrayList getAllInformation(String searchTerm) throws IOException, ParserConfigurationException, SAXException, SQLException 
    {
		tweets = new ArrayList<Tweet>();
		
    	tg = new TweetGrabber();
    	xmlo = new XMLoutput();
    	nf = new NoiseFilter();
    	sf = new SentFilter();
    	sqlw = new SQLwork();
    	
    	// User enter search term
    	// BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    	// System.out.print("Enter searchword: ");
        // String search = br.readLine();
        
        // Execute search with users term
        tg.grabber(searchTerm);
        tg.parser();
        
        
        tweets = nf.removeNoise(tweets);
        tweets = sf.getSentiment(tweets);
        xmlo.generator(tweets);
		
        return tweets;
    }
 
 
    private void grabber(String s) 
    {
        BufferedReader br = null;
        InputStreamReader isr = null;
        URL url = null;
        
        /* Building the search-URL for twitter
         * Result_type = recent, gives only the latest tweets
         * rpp = 100, shows 100 tweets on one page so we get the latest 100 */
        try 
        {
            url = new URL("http://search.twitter.com/search.atom?q="+s+"&result_type=recent&rpp=100");
        } 
        catch (MalformedURLException e) 
        {
            e.printStackTrace();
        }
 
        if(url != null) 
        {
            try 
            {
                isr = new InputStreamReader(url.openStream());
            } 
            catch (IOException e1) 
            {
                e1.printStackTrace();
            }
            
            /* Creating a temp.txt for the search result
             * Just a first try to see how the output can be changed
             * And to have a better overview of the result itself */
            br = new BufferedReader(isr);
            String line = null;
            FileOutputStream output = null;
            
            try 
            {
            	output = new FileOutputStream(file);
            } 
            catch (FileNotFoundException e1) 
            {
                e1.printStackTrace();
            }
            
            DataOutputStream out = new DataOutputStream(output);
            
            try 
            {
                while((line = br.readLine()) != null) 
                {
                	try 
                    {
                		out.writeBytes(line);
                    }
                    catch (IOException e) 
                    {
                    }
                }
 
            } 
            catch (IOException e2) 
            {
                e2.printStackTrace();
            }
        }
    }
    
    private void parser() throws ParserConfigurationException, SAXException, IOException
    {
    	DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    	DocumentBuilder builder = dbFactory.newDocumentBuilder();
    	Document doc = builder.parse(file);
    	
    	Node node = doc.getFirstChild();        
        NodeList rootNodes = node.getChildNodes();
        
        for(int i = 0; i < rootNodes.getLength(); i++)
        {
        	if(rootNodes.item(i).toString().contains("entry"))
        	{
        		this.tempTweet = new Tweet();
        		
        		this.tempTweet.setUser(rootNodes.item(i).getChildNodes().item(11).getChildNodes().item(0).getTextContent());
        		this.tempTweet.setText(rootNodes.item(i).getChildNodes().item(4).getTextContent());
        		this.tempTweet.setLocation(rootNodes.item(i).getChildNodes().item(7).getTextContent());
        		this.tempTweet.setUpdated(rootNodes.item(i).getChildNodes().item(5).getTextContent());
        		this.tempTweet.setPicture(rootNodes.item(i).getChildNodes().item(6).getAttributes().getNamedItem("href").getTextContent());        		
        		this.tempTweet.setLanguage(rootNodes.item(i).getChildNodes().item(10).getTextContent());        		
        		this.tempTweet.setRating(0);
        		
        		this.tweets.add(this.tempTweet);
        	}
        }
    }
}